package cn.dyp.com.manualcontrol.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.ArrayList;

import cn.dyp.com.manualcontrol.ClientApp;
import cn.dyp.com.manualcontrol.R;
import cn.dyp.com.manualcontrol.adpter.ViewPagerAdapater;
import cn.dyp.com.manualcontrol.bean.ControllerStatus;
import cn.dyp.com.manualcontrol.bean.ControllerUiData;
import cn.dyp.com.manualcontrol.dialog.IpSetDialog;
import cn.dyp.com.manualcontrol.request.BaseRequest;
import cn.dyp.com.manualcontrol.request.ControlRequest;
import cn.dyp.com.manualcontrol.request.GetControllerStatusRequest;
import cn.dyp.com.manualcontrol.request.RequestThread;

/*程序控制 Activity
* 先设置ip，保存ip，根据ip获得设备控制状态
*/

public class MainActivity extends AppCompatActivity implements OnPageChangeListener {
	private ViewPager mViewPager;
	private ViewPagerAdapater mAdapater;
	private ArrayList<ControllerUiData> mDataList;
	private ControllerUiData mBlowerCtrl;
	private ControllerUiData mRoadlampCtrl;
	private ControllerUiData mWaterCtrl;
	private ControllerUiData mBuzzerCtrl;
	// 获取控制器状态的请求对象
	private GetControllerStatusRequest mGetControllerStatusRequest;
	// 设置控制器状态的请求对象
	private ControlRequest mControlRequest;
	private RequestThread mThread;
	private ClientApp mApp;
	private ProgressDialog mDialog;
	private LinearLayout mLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportActionBar().hide();
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_main);
		mApp = (ClientApp) getApplication();
		mApp.setActivity(this);
		IpSetDialog ipDialog = new IpSetDialog(this);
		ipDialog.setCancelable(false);
		ipDialog.show(getFragmentManager(), "dialog");
		initData();
		setRequest();
		iniView();
	}

	/**
	 * 设置请求对象
	 * 
	 */
	private void setRequest() {
		// 设置获取控制器状态请求对象
		mGetControllerStatusRequest = new GetControllerStatusRequest("");
		mGetControllerStatusRequest.setControllerStatus(mApp
				.getControllerStatus());
		mGetControllerStatusRequest
				.setOnResponseEventListener(new BaseRequest.OnResponseEventListener() {

					@Override
					public void onResponse(BaseRequest request,
							BaseRequest.RequestResult result) {
						mDialog.dismiss();
						if (mGetControllerStatusRequest.isSuccess()) {
							// 获取控制器状态以后，刷新所有控制器的开关状态
							ControllerStatus status = mGetControllerStatusRequest
									.getControllerStatus();
							mBlowerCtrl.isOpen = status.getBlower();
							mRoadlampCtrl.isOpen = status.getRoadLamp();
							mWaterCtrl.isOpen = status.getWaterPump();
							mBuzzerCtrl.isOpen = status.getBuzzer();
							mAdapater.notifyDataSetChanged();
						}
					}
				});
		// 设置控制器状态请求对象
		mControlRequest = new ControlRequest("");
		mControlRequest
				.setOnResponseEventListener(new BaseRequest.OnResponseEventListener() {

					@Override
					public void onResponse(BaseRequest request,
							BaseRequest.RequestResult result) {
						if (mControlRequest.isSuccess()) {
							// 控制器请求成功以后，等待1秒钟再向服务器查询控制器状态（因为控制是异步操作）
							RequestThread thread = new RequestThread(
									MainActivity.this, mApp.getHandler());
							thread.setRequest(mGetControllerStatusRequest);
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							thread.start();
						} else {
							mDialog.dismiss();
						}
					}
				});
	}

	/**
	 * 初始化控件
	 * 
	 */
	private void iniView() {
		mViewPager = (ViewPager) findViewById(R.id.sensor_show);
		mLayout = (LinearLayout) findViewById(R.id.indicator);

		mLayout.removeAllViews();
		setIndicator();

		mAdapater = new ViewPagerAdapater(this, mDataList, new ViewPagerAdapater.OnItemOnClick() {
			@Override
			public void click(int position) {
				ControllerUiData data = mDataList.get(position);
				int oldStatus = data.isOpen;
				data.isOpen = (data.isOpen + 1) % 2;
				mControlRequest.resetRequest();
				if (data == mBlowerCtrl) {
					mControlRequest.setBlower(mBlowerCtrl.isOpen);
				} else if (data == mRoadlampCtrl) {
					mControlRequest.setRoadLamp(mRoadlampCtrl.isOpen);
				} else if (data == mWaterCtrl) {
					mControlRequest.setWaterPump(mWaterCtrl.isOpen);
				} else if (data == mBuzzerCtrl) {
					mControlRequest.setBuzzer(mBuzzerCtrl.isOpen);
				}
				startRequest(mControlRequest);
				mDialog.show();
				data.isOpen = oldStatus;
			}
		});
		mViewPager.setAdapter(mAdapater);
		mViewPager.setOnPageChangeListener(this);
		startRequest(mGetControllerStatusRequest);

		mDialog = new ProgressDialog(this);
		mDialog.setMessage(getString(R.string.waite));
	}

	/**
	 * 设置视图下方指示器
	 * 
	 */
	private void setIndicator() {
		for (int i = 0; i < mDataList.size(); i++) {
			ImageView imageView = new ImageView(this);
			if (i == 0) {
				imageView.setImageResource(R.drawable.page_indicator_focused);
			} else {
				imageView.setImageResource(R.drawable.page_indicator_unfocused);
			}
			mLayout.addView(imageView);
		}
	}

	/**
	 * 设置网络连接的线程
	 * 
	 * @param request
	 *            请求对象
	 */
	private void startRequest(BaseRequest request) {
		if (request != null) {
			mThread = new RequestThread(this, mApp.getHandler());
			mThread.setRequest(request);
			mThread.start();
		}
	}

	/**
	 * 构建界面数据
	 * 
	 */
	private void initData() {
		mDataList = new ArrayList<ControllerUiData>();
		mBlowerCtrl = new ControllerUiData(getString(R.string.blower),
				R.drawable.blower_on, R.drawable.blower_off);
		mRoadlampCtrl = new ControllerUiData(getString(R.string.road_lamp),
				R.drawable.roadlamp_on, R.drawable.roadlamp_off);
		mWaterCtrl = new ControllerUiData(getString(R.string.water_pump),
				R.drawable.water_pump_on, R.drawable.water_pump_off);
		mBuzzerCtrl = new ControllerUiData(getString(R.string.buzzer),
				R.drawable.buzzer_on, R.drawable.buzzer_off);
		mDataList.add(mBlowerCtrl);
		mDataList.add(mRoadlampCtrl);
		mDataList.add(mWaterCtrl);
		mDataList.add(mBuzzerCtrl);
	}

	/**
	 * 滚动状态发生变化时调用
	 * 
	 * @see OnPageChangeListener#onPageScrollStateChanged(int)
	 */
	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	/**
	 * 当前页滚动时调用(不论是人为的触摸滚动还是程序自己执行的滚动)
	 * 
	 * @see OnPageChangeListener#onPageScrolled(int,
	 *      float, int)
	 */
	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	/**
	 * 新页面选中时调用
	 * 
	 * @see OnPageChangeListener#onPageSelected(int)
	 */
	@Override
	public void onPageSelected(int arg0) {
		selectIndicator(arg0);
	}

	/**
	 * 显示指示位置，更改标点样式
	 * 
	 * @param arg0
	 *            需要显示的指示器序号
	 */
	private void selectIndicator(int arg0) {
		for (int i = 0; i < mLayout.getChildCount(); i++) {
			ImageView imageView = (ImageView) mLayout.getChildAt(i);
			if (i == arg0) {
				imageView.setImageResource(R.drawable.page_indicator_focused);
			} else {
				imageView.setImageResource(R.drawable.page_indicator_unfocused);
			}
		}
	}
}
